package whr.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import whr.common.exception.Exception;
import whr.common.utils.Constant;
import whr.common.utils.PageUtils;
import whr.common.utils.Query;
import whr.common.utils.ResponseApi;
import whr.modules.sys.dao.SysUserDao;
import whr.modules.sys.entity.SysUserEntity;
import whr.modules.sys.service.SysRoleService;
import whr.modules.sys.service.SysUserRoleService;
import whr.modules.sys.service.SysUserService;

import javax.xml.transform.Result;
import java.io.File;
import java.io.IOException;
import java.util.*;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserService sysUserService;
	@Value("${web.upload-path}")
	private String uploadPath;


	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		String mobile = (String)params.get("mobile");
		Long createUserId = (Long)params.get("createUserId");

//		System.out.println("username:"+username);

		IPage<SysUserEntity> page = this.page(
			new Query<SysUserEntity>().getPage(params),
			new QueryWrapper<SysUserEntity>()
				.like(StringUtils.isNotBlank(username),"username", username)
					.like(StringUtils.isNotBlank(mobile),"mobile", mobile)
				.eq(createUserId != null,"create_user_id", createUserId)
		);
		// 对查询结果中的每条记录进行密码、邮箱、盐值脱敏处理
		// 遍历每一条数据 通过userId查询每个用户的角色列表
		page.getRecords().forEach(user -> {
			user.setPassword("******");  // 将密码替换为星号或其他占位符
			user.setSalt("******");  // 将盐替换为星号或其他占位符
			List<Long> roleList = sysUserRoleService.queryRoleIdList(user.getUserId());
			user.setRoleIdList(roleList);
		});

//		System.out.println("Returning data: " + page.getRecords());
//		System.out.println("Total count: " + page.getTotal());
		return new PageUtils(page);
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	@Transactional
	public void saveUser(SysUserEntity user) {

		//设置邮箱不重复
		if(sysUserDao.getUserEmail(user.getEmail()) != null){
			throw new Exception("该邮箱已存在，添加失败！");
		}else {
			//如果邮箱没有重复，则保存用户信息
			user.setCreateTime(new Date());
			//sha256加密
			String salt = RandomStringUtils.randomAlphanumeric(20);
			user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
			user.setSalt(salt);
			this.save(user);
			//检查角色是否越权
			checkRole(user);
			//保存用户与角色关系
			sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		}

	}

	@Override
	@Transactional
	public void update(SysUserEntity user) {
		SysUserEntity byId = sysUserService.getById(user);
		if(!byId.getEmail().equals(user.getEmail())){
			if(sysUserDao.getUserEmail(user.getEmail()) != null) {
				throw new Exception("该邮箱已存在，修改失败！");
			}
		}
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		this.updateById(user);

		//检查角色是否越权
		checkRole(user);

		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public void deleteBatch(Long[] userId) {
		this.removeByIds(Arrays.asList(userId));
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}



	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		if(user.getRoleIdList() == null || user.getRoleIdList().size() == 0){
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if(user.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}

		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if(!roleIdList.containsAll(user.getRoleIdList())){
			throw new Exception("新增用户所选角色，不是本人创建");
		}
	}

	/**
	 * 获取用户数量
	 * @return
	 */
	@Override
	public Object getUserCount() {
		return baseMapper.getUserCount();
	}

	@Override
	public List<Integer> getUserCountByDept() {
		return sysUserDao.getUserCountByDept();
	}

	@Override
	public List<SysUserEntity> selectUserListInIds(List<Integer> ids) {

		QueryWrapper queryWrapper=new QueryWrapper();
		queryWrapper.in("user_id",ids);
		List<SysUserEntity> userEntities = sysUserDao.selectList(queryWrapper);
		return userEntities;
	}

	@Override
	@ApiOperation(value = "根据用户id修改用户头像", notes = "根据用户id修改用户头像")
	public ResponseApi updateUserAvatarById(List<MultipartFile> files, int userId) {

//		本地上传
        File folder = new File(uploadPath);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
		// 校验头像
		if (files.size() > 1) {
			return ResponseApi.failed("头像只能上传一个！");
		}

		if (files.isEmpty() || files.get(0).isEmpty()) {
			return ResponseApi.failed("文件为空！");
		}

		MultipartFile file = files.get(0);

		// 校验文件格式
		String filename = file.getOriginalFilename();
		if (filename == null || !filename.matches("^.+\\.(jpg|jpeg|png|gif)$")) {
			return ResponseApi.failed("头像格式有误！");
		}

		// 生成唯一的文件名
		String originalFilename = file.getOriginalFilename();
		String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
		String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

		// 将文件保存到本地
//		String localPath = "D:\\upload\\" + uniqueFilename;
		String avatarUrl = "http://localhost:8080/catanddog/avatar/" + uniqueFilename+"?token=18116afae9d025dba26d76b5d4c9b958";   // 此处需要修改为实际路径

		try {
			// 将文件保存到本地
			file.transferTo(new File(uploadPath));
		} catch (IOException e) {
			throw new RuntimeException("文件上传失败", e);
		}

		// 更新头像
		int user = sysUserDao.updateUserAvatarById(avatarUrl, userId);

		// 判断用户是否存在
		if (user == 0) {
			// 用户不存在，返回错误信息
			return ResponseApi.failed("用户不存在！");
		}

		return ResponseApi.success("修改头像成功！" + uniqueFilename);
	}

}